//
//  XLHomeViewController.swift
//  SinaProjectTest
//
//  Created by zhanghaifeng on 16/10/22.
//  Copyright © 2016年 BBSWaitting. All rights reserved.
//

import UIKit


private let homeStatusCellID = "homeStatusCellID"

class XLHomeViewController: XLVistorViewController {
    
    // 保存微博数据数组
    let listViewModel:XLHomeListViewModel = XLHomeListViewModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 判断是否登录
        if !isLogin{
            // 设置访客视图信息
            vistorView?.setVistorViewInfo(imgNamed: nil, title: nil)
            return
        }
        setupUI()
        // 加载首页数据
        loadDataFromListViewController()
    }
    @objc private func leftClick(){
        print("左侧按钮被点击了")
    }
    @objc private func rightClick(){
        print("右侧按钮被点击了")
        let tmpVc = XLTempViewController()
        tmpVc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(tmpVc, animated: true)
    }
    // MARK: 设置视图
    private func setupUI(){
        setupNav()
        setupTableViewInfo()
        // 添加 tipLabel
        self.navigationController?.view.insertSubview(tipLabel, belowSubview: (self.navigationController?.navigationBar)!)
        // maxY 获取最大Y值
        tipLabel.frame = CGRect(x: 0, y: (self.navigationController?.navigationBar.frame.maxY)! - 35, width: (self.navigationController?.navigationBar.frame.width)!, height: 35)
    }
    // 设置tableView的相关信息
    private func setupTableViewInfo(){
        // 遵守数据源
        tableView.dataSource = self
        tableView.delegate = self
        // 注册cell
        tableView.register(XLHomeStatusTableViewCell.self, forCellReuseIdentifier: homeStatusCellID)
//        tableView.rowHeight = 300
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
        // 设置tableView 的分割线的样式 为none
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        
        // 设置footerView
        tableView.tableFooterView = bottomView
        // 添加系统控件下拉刷新控件
        tableView.addSubview(refreshControl)
        refreshControl.addTarget(self, action: #selector(loadDataFromListViewController), for: UIControlEvents.valueChanged)
        
    }
    // MAKR: 设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(setHighLightImageName: "navigationbar_pop", title: nil, target: self, action: #selector(leftClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(setHighLightImageName: "navigationbar_friendsearch", target: self, action: #selector(rightClick))
    }
    
    // MARK:  tipLabel 开启动画
    fileprivate func startTipAnimation(message: String){
        
        if tipLabel.isHidden == false{
            // 正在执行动画
            return
        }
        
        tipLabel.isHidden = false
        tipLabel.text = message
        UIView.animate(withDuration: 1.0, animations: { 
            self.tipLabel.transform = CGAffineTransform(translationX: 0, y: self.tipLabel.frame.height)
            }) { (_) in
                UIView.animate(withDuration: 1.0, animations: { 
                    self.tipLabel.transform = CGAffineTransform.identity
                    }, completion: { (_) in
                        self.tipLabel.isHidden = true
                })
        }
    }
    
    
    // MARK: 懒加载控件
    // 菊花控件
    lazy var bottomView: UIActivityIndicatorView = {
        
       let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        // 设置颜色
        view.backgroundColor = UIColor.purple
        return view
    }()
    // 系统下拉刷新控件
//    fileprivate lazy var refreshControl: UIRefreshControl = UIRefreshControl()
    // 自定义下拉刷新控件
    fileprivate lazy var refreshControl: XLRefreshControl = XLRefreshControl()
    // tipLabel
    fileprivate lazy var tipLabel: UILabel = {
        
        let label = UILabel(text: "没有加载到微博数据", fontSize: 11, textColor: UIColor.white)
        label.backgroundColor = UIColor.orange
        label.textAlignment = .center
        // 默认隐藏
        label.isHidden = true
        return label
        
    }()
    
    
    
}

// 加载首页数据
extension XLHomeViewController{
    // 加载首页数据
    func loadDataFromListViewController(){
        
        listViewModel.loadHomeListData(isPullUp: bottomView.isAnimating) { (isSuccess, message) in
            // 不是上拉加载 执行tip动画
            if !self.bottomView.isAnimating{
                self.startTipAnimation(message: message)
            }
            
            if !isSuccess{
                print("加载失败")
                
            }else{
                // 刷新UI
                self.tableView.reloadData()
            }
            self.endRefreshing()
        }
        
    }
    
    
    // 停止下拉和上啦动画
    func endRefreshing(){
        // 停止动画
        self.bottomView.stopAnimating()
        // 下拉刷新也要停止
        self.refreshControl.endRefreshing()
        
    }
}

//MARK: - UITableViewDataSource

extension XLHomeViewController: UITableViewDataSource, UITableViewDelegate{
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //创建cell
        let cell = tableView.dequeueReusableCell(withIdentifier: homeStatusCellID, for: indexPath) as! XLHomeStatusTableViewCell
        // 取消选中行的效果 cell.selectionStyle = UITableViewCellSelectionStyle(rawValue: 0)!
        // 给cell 赋值
        cell.statusViewModel = listViewModel.dataArray[indexPath.row]
        cell.selectionStyle = UITableViewCellSelectionStyle(rawValue: 0)!

        return cell
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row == listViewModel.dataArray.count - 1 && !bottomView.isAnimating{
            // 开启动画
            bottomView.startAnimating()
            // 请求数据
            loadDataFromListViewController()
        }
    }
    
    // 插入view 解决显示界面的 cell 线
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view: UIView = UIView()
        return view
    }
}



